<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑分配' : '新增分配'"
    width="800px"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="人员姓名" prop="name">
            <el-input v-model="formData.name" placeholder="请输入人员姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工号" prop="employeeId">
            <el-input v-model="formData.employeeId" placeholder="请输入工号" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所属部门" prop="department">
            <el-select v-model="formData.department" placeholder="请选择所属部门" style="width: 100%">
              <el-option label="管理部" value="管理部" />
              <el-option label="运行部" value="运行部" />
              <el-option label="维护部" value="维护部" />
              <el-option label="安全部" value="安全部" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="职位" prop="position">
            <el-input v-model="formData.position" placeholder="请输入职位" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="formData.phone" placeholder="请输入联系电话" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="分配时间" prop="assignDate">
            <el-date-picker
              v-model="formData.assignDate"
              type="datetime"
              placeholder="请选择分配时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="分配责任" prop="responsibilities">
        <el-select
          v-model="formData.responsibilities"
          multiple
          placeholder="请选择分配责任"
          style="width: 100%"
        >
          <el-option
            v-for="responsibility in responsibilityOptions"
            :key="responsibility.value"
            :label="responsibility.label"
            :value="responsibility.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

interface Props {
  visible: boolean
  assignmentData?: any
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = withDefaults(defineProps<Props>(), {
  assignmentData: null
})

const emit = defineEmits<Emits>()

const formRef = ref<FormInstance>()

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const isEdit = computed(() => !!props.assignmentData?.id)

const formData = reactive({
  name: '',
  employeeId: '',
  department: '',
  position: '',
  phone: '',
  assignDate: '',
  responsibilities: []
})

// 责任选项（实际项目中应该从API获取）
const responsibilityOptions = ref([
  { label: '水库安全运行责任', value: '水库安全运行责任' },
  { label: '设备维护责任', value: '设备维护责任' },
  { label: '应急处置责任', value: '应急处置责任' },
  { label: '技术支持责任', value: '技术支持责任' },
  { label: '巡检监测责任', value: '巡检监测责任' },
  { label: '数据记录责任', value: '数据记录责任' }
])

const formRules: FormRules = {
  name: [
    { required: true, message: '请输入人员姓名', trigger: 'blur' }
  ],
  employeeId: [
    { required: true, message: '请输入工号', trigger: 'blur' }
  ],
  department: [
    { required: true, message: '请选择所属部门', trigger: 'change' }
  ],
  position: [
    { required: true, message: '请输入职位', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  assignDate: [
    { required: true, message: '请选择分配时间', trigger: 'change' }
  ],
  responsibilities: [
    { required: true, message: '请选择分配责任', trigger: 'change' }
  ]
}

// 重置表单函数
const resetForm = () => {
  Object.assign(formData, {
    name: '',
    employeeId: '',
    department: '',
    position: '',
    phone: '',
    assignDate: '',
    responsibilities: []
  })
  formRef.value?.clearValidate()
}

// 监听数据变化，初始化表单
watch(() => props.assignmentData, (newData) => {
  if (newData) {
    Object.assign(formData, {
      name: newData.name || '',
      employeeId: newData.employeeId || '',
      department: newData.department || '',
      position: newData.position || '',
      phone: newData.phone || '',
      assignDate: newData.assignDate || '',
      responsibilities: newData.responsibilities || []
    })
  } else {
    resetForm()
  }
}, { immediate: true })

const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    // 这里应该调用API保存数据
    console.log('保存人员分配数据:', formData)
    
    ElMessage.success(isEdit.value ? '编辑成功' : '新增成功')
    emit('success')
    handleClose()
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>